<?php
/**
 * Description: 事业单位题库工具方法
 * User: devforma
 * Date: 2016/12/5
 * Time: 17:39
 */
class InstitutionUtils {

    /**
     * 根据题目id获取题目内容
     *
     * @param array $ids 题目id数组
     * @return array
     */
    public static function getQuestionsByInstitutionIds($ids) {
        global $cmsdb;

        if (!is_array($ids) || empty($ids))
            return array();

        $idsStr = implode(',', $ids);           //string(26) "3,1,7,5,8,9,10,11,12,13,14"

        $notes = self::getNotesByInstitutionQuestions($idsStr);

        $sql = 'SELECT * FROM `institution_questions` WHERE `id` IN (' . $idsStr . ') ORDER BY FIELD(`id`, ' . $idsStr . ')';
        $data = $cmsdb->getResults($sql);
        $list = array();
        $poll = array(); //滤重
        foreach ($data as $q) {
            $options = json_decode($q->options, true);
            $qid = intval($q->id);
            if (in_array($qid, $poll, true)) {
                continue;
            }
            $poll[] = $qid;
            $answer = correctAnswer(trim($q->answer));
            $list[] = array(
                'id'          => $qid,
                'type'        => $q->type,
                'material'    => getSecureUrl(html2text(self::getMaterialByInstitutionId($q->material_id))),
                'question'    => getSecureUrl(html2text($q->question)),
                'option_a'    => getSecureUrl(html2text(ltrim(ltrim($options[0], 'A'), '.'))),
                'option_b'    => getSecureUrl(html2text(ltrim(ltrim($options[1], 'B'), '.'))),
                'option_c'    => getSecureUrl(html2text(ltrim(ltrim($options[2], 'C'), '.'))),
                'option_d'    => getSecureUrl(html2text(ltrim(ltrim($options[3], 'D'), '.'))),
                'answer'      => $answer,
                'analysis'    => $q->status == 1 ? getSecureUrl(html2text($q->analysis)) : '',
                'note_id'     => intval($notes[$qid]['id'][0]),
                'note_ids'    => $notes[$qid]['id'],
                'note_name'   => $notes[$qid]['name'],
                'material_id' => (int)$q->material_id,
            );
        }

        return $list;
    }

    /**
     * 获取题目的知识点
     *
     * @param array|string $ids 多个ID的字符串以逗号分隔
     * @return array
     */
    public static function getNotesByInstitutionQuestions($ids) {
        global $cmsdb;

        $data = array();
        if (empty($ids)) return $data;

        if (is_array($ids)) $ids = implode(',', $ids);

        $sql = "SELECT r.*, t.term_name AS name FROM `{$cmsdb->insQueNoteR}` r " .
            "LEFT JOIN `institution_note_term` t ON(r.note_id=t.id) " .
            "WHERE `question_id` IN($ids)";
        $results = $cmsdb->table()->cache()->raw($sql)->get();
        if (!$results) return $data;

        foreach ($results as $r) {
            $data[$r->question_id]['id'][] = intval($r->note_id);

            if (array_key_exists('name', $data[$r->question_id])) {
                $data[$r->question_id]['name'] .= ',' . $r->name;
            } else {
                $data[$r->question_id]['name'] = $r->name;
            }
        }

        //补齐无关联的题的信息
        $ids = explode(',', $ids);
        foreach ($ids as $qid) {
            if (array_key_exists($qid, $data)) continue;
            $data[$qid] = array('id' => array(0), 'name' => '');
        }
        return $data;
    }

    /**
     * 获取用户统计数据
     *
     * @param int $userId 用户id
     * @return array
     */
    public static function getUserData($userId) {
        global $uddb;

        $userData = $uddb->getRow('SELECT * FROM `institution_user_data` WHERE `user_id`=:uid', [':uid' => $userId], PDO::FETCH_ASSOC);

        //用户首次提交，创建userdata数据
        if (empty($userData)) {
            $userNotes = [];
            $notes = self::getNoteHierarchy();
            foreach ($notes as $note) {
                if ($note['term_type'] == 1) {
                    $userNotes[$note['id']] = [0, 0]; //总题量，答对题量
                }
            }

            $now = date('Y-m-d H:i:s');
            $userData = [
                'user_id'         => $userId,
                'note_info'       => json_encode($userNotes),
                'created_at'      => $now,
                'score'           => 0,
                'total_count'     => 0,
                'right_count'     => 0,
                'accuracy'        => 0,
                'last_updated_at' => $now
            ];
            $uddb->insert('institution_user_data', $userData);
        }

        return $userData;
    }

    /**
     * 更新用户统计信息
     *
     * @param int $userId 用户id
     * @param array $newData 待更新数据
     */
    public static function updateUserData($userId, $newData) {
        global $uddb;

        $uddb->update('institution_user_data', $newData, ['user_id' => $userId]);
    }

    /**
     * 根据 material_id 获取 material信息
     *
     * @param $material_id
     * @return string|null
     */
    public static function getMaterialByInstitutionId($material_id) {
        global $cmsdb;
        if (!empty($material_id)) {
            $cacheKey = 'func:getMaterialByInstitutionId:' . $material_id;

            $dataCache = cacheGet($cacheKey);
            if (!empty($dataCache))
                return $dataCache;

            $material = $cmsdb->getVar('SELECT `material` FROM `institution_question_material` WHERE `id`=:material_id',
                array(':material_id' => $material_id));
            if (!empty($material)) {
                cacheAdd($cacheKey, $material, 30 * 60);
                return $material;
            }
        }
        return null;
    }

    /**
     * 根据试卷类型名称或ID获取类型描述
     *
     * @param string $NameOrId 类型名称或id
     * @return Object
     */
    function getPaperType($NameOrId) {
        global $uddb;

        $cacheKey = 'institution_paperType';
        if (($value = cacheGet($cacheKey)) != null) {
            return $value[$NameOrId];
        } else {
            $value = array();
            $types = $uddb->getResults('SELECT * FROM `institution_exercise_type` WHERE 1');
            foreach ($types as $type) {
                $value["$type->type_name"] = $type;
                $value["$type->id"] = $type;
            }

            cacheAdd($cacheKey, $value, 48 * 60 * 60);
            return $value[$NameOrId];
        }
    }

    /**
     * 获取事业单位题库知识点数据
     *
     * @return array
     */
    public static function getNoteHierarchy() {
        global $cmsdb;
        $cacheKey = 'institution:func:getNoteHierarchy';

        if (($noteData = cacheGet($cacheKey)) == null) {

            $sql = 'SELECT * FROM `interview_note_term` WHERE `term_status`=1';
            $notes = $cmsdb->getResults($sql);

            if (empty($notes))
                return array();

            $noteData = array();
            foreach ($notes as $note) {
                $noteData[$note->id] = array(
                    'id'        => (int)$note->id,
                    'name'      => $note->term_name,
                    'parent_id' => (int)$note->parent_term_id,
                    'note_desc' => $note->note_desc,
                    'term_type' => (int)$note->term_type,
                    'childs'    => array()
                );
            }

            cacheAdd($cacheKey, $noteData, 24*60*60);
        }

        return $noteData;
    }

    /**
     *根据试卷id获取评分
     *papram
     *
     */
    public static function getInstitutionEvaluate($paperId) {
        global $uddb;
        $cacheKey = 'institution:func:getInstitutionEvaluate'.$paperId;

        if(($evaluateData = cacheGet($cacheKey)) == null) {

            //获取已做体型的所有评分
            $evaluates = $uddb->getCol('SELECT `evaluate` FROM `institution_user_paper` WHERE `status`= 1 AND `paper_id`=:id', array(':id' => $paperId));
            if(empty($evaluates))
                return array();
            foreach($evaluates as $v){
                if(isset($evaluateData[intval($v)]))
                    $evaluateData[intval($v)]++;
                else
                    $evaluateData[intval($v)] = 1;
            }
            cacheAdd($cacheKey, $evaluateData, 24*60*60);
        }
        return $evaluateData;
    }

    /**
     * 更新试卷排名信息
     *
     * @param int $paperId 试卷id
     * @param float $score 分数
     */
    public static function updateInstitutionEvaluate($paperId, $score) {
        $cacheKay = 'institution:func:getInstitutionEvaluate'.$paperId;
        if($evaluateData = cacheGet($cacheKay)) {
            if(isset($evaluateData[intval($score)])) {
                $evaluateData[intval($score)]++;
            } else {
                $evaluateData[intval($score)] = 1;
            }

            cacheSet($cacheKay, $evaluateData, 24*60*60);
        }
    }

    /**
     * 获取事业单位题库试卷信息
     * 
     * @param int $paperId 试卷id
     * @return array
     */
    public static function getPaperInfo($paperId) {
        global $cmsdb;

        $data = $cmsdb->getRow('SELECT * FROM `institution_papers` WHERE `id`=:pid', [':pid' => $paperId]);

        return [
            'id'   => (int)$data->id,
            'name' => $data->paper_name
        ];
    }
}